<script setup>
import api from '../api/roomapi.js'
import billApi from '../api/billapi.js'
import {ref, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import lodash from 'lodash'
const isAdd=ref(false);
//定义绑定的数据
//表格中的数据
const tableData = ref([]);

const total=ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
// 添加账单对话框显示状态
const billDialogVisible = ref(false);
//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  room_number: '',
  status: '',
  electronics: '',
  floor:'' ,
  price: '',
  type: '',
});

//要修改或者新增的数据
const obj = ref({});

// 账单数据
const billObj = ref({
  staff_id: '', // 使用 staff_id 而不是 user_id
  room_fee: '',
  extra_fee: 0,
  bill_time: ''
});

const reseve=ref({});

const defaultImageUrl=ref('');
//上传图片相关
const uploadDialogVisible = ref(false);
const currentStaffId = ref(null);
const uploadImageUrl = ref('');

const search = async () => {
  try {
    // 构造查询参数，过滤掉空值
    const params = {};
    Object.keys(searchObj.value).forEach(key => {
      if (searchObj.value[key] !== '' && searchObj.value[key] !== null && searchObj.value[key] !== undefined) {
        params[key] = searchObj.value[key];
      }
    });

    console.log('搜索参数:', params);
    var result = await api.page(params);
    console.log('API返回结果:', result);
    if (result && result.data) {
      // 检查返回的数据结构
      console.log('表格数据结构:', result.data);
      tableData.value = result.data;
      console.log("表格数据：", tableData.value);
      total.value = result.count || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("查询出错:", error);
    tableData.value = [];
    total.value = 0;
    ElMessage.error("查询数据失败");
  }
}
//页面加载后要挂载的数据
onMounted(async () => {
  await search();
});
//定义方法

const handleSizeChange=()=>{
  search();
}
const handleCurrentChange=()=>{
  search();
}

const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}

const resetSearch = () => {
  searchObj.value = {
    current: 1,
    limit: 10,
    room_number: '',
    status: '',
    electronics: '',
    floor:'',
    price: '',
    type: ''
  };
  search();
}

const save = async () => {
  try {
    if (isAdd.value) {
      // 新增操作
      await api.add(obj.value);
      ElMessage.success("新增成功");
    } else {
      // 编辑操作
      await api.edit(obj.value);
      ElMessage.success("修改成功");
    }
    await search(); // 刷新表格
    editWinVisible.value = false; // 关闭编辑对话框
  } catch (error) {
    console.error(isAdd.value ? "新增失败" : "编辑失败", error);
    ElMessage.error(isAdd.value ? "新增失败，请检查网络或数据格式" : "修改失败，请检查网络或数据格式");
  }
}

const del = (row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.del(row.id);
        //重新加载数据
        //设置从第一页开始查询
        searchObj.value.current = 1;
        await search();
      })
      .catch(() => {
      })
}

const handlerAdd = async () => {
  obj.value = {room_number: '', status:'', electronics: '', floor: '', price: '', type: ''};
  isAdd.value=true;
  editWinVisible.value = true;
}

const edit = (row) => {
  obj.value = lodash.clone(row);
  isAdd.value = false;
  editWinVisible.value = true;
}

// 打开账单对话框
const openBillDialog = (row) => {
  obj.value = lodash.clone(row); // 保存当前房间信息
  billObj.value = {
    staff_id: '', // 用户ID字段应该是 staff_id
    room_fee: row.price || (row.roomType ? row.roomType.price : 0),
    extra_fee: 0,
    bill_time: '' // 不再设置默认值，让用户选择
  };
  billDialogVisible.value = true;
}

// 提交账单
const submitBill = async () => {
  try {
    // 处理提交的数据
    const submitData = {...billObj.value};

    // 确保数值字段是数字类型
    submitData.room_fee = Number(submitData.room_fee);
    submitData.extra_fee = Number(submitData.extra_fee);

    // 处理日期格式
    if (submitData.bill_time instanceof Date) {
      const date = submitData.bill_time;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      submitData.bill_time = `${year}-${month}-${day} 00:00:00`;
    } else if (typeof submitData.bill_time === 'string' && submitData.bill_time.match(/^\d{4}-\d{2}-\d{2}$/)) {
      // 如果是 YYYY-MM-DD 格式的字符串，补充时间部分
      submitData.bill_time = `${submitData.bill_time} 00:00:00`;
    }

    await billApi.add(submitData);

    // 更新房间状态为"有人"
    const roomUpdateData = {
      id: obj.value.id,
      room_number: obj.value.room_number,
      status: '有人',
      electronics: obj.value.electronics,
      floor: obj.value.floor
    };

    // 只有当这些字段存在时才添加它们
    if (obj.value.price !== undefined) {
      roomUpdateData.price = obj.value.price;
    }
    if (obj.value.type !== undefined) {
      roomUpdateData.type = obj.value.type;
    }

    await api.edit(roomUpdateData);

    ElMessage.success("账单创建成功，房间状态已更新");
    billDialogVisible.value = false;
    await search(); // 刷新表格数据
  } catch (error) {
    console.error("账单创建失败", error);
    ElMessage.error("账单创建失败，请检查网络或数据格式");
  }
}
// //图片加载失败处理
// const handleImageError = (event) => {
//   event.target.src = defaultImageUrl.value;
// };
// //打开上传图片对话框
// const openUploadDialog=(staffId)=>{
//   currentStaffId.value=staffId;
//   uploadDialogVisible.value=true;
// };
// //上传图片到数据库
// const uploadImage=async ()=>{
//   if (!uploadImageUrl.value){
//     ElMessage.error("请输入图片URL");
//     return;
//   }
//   try{
//     await api.edit({id:currentStaffId.value, imageUrl:uploadImageUrl.value})
//     ElMessage.success("图片上传成功");
//     uploadDialogVisible.value=false;
//     uploadImageUrl.value='';
//     await search();
//   }catch (error){
//     ElMessage.error("图片上传失败");
//     console.error(error);
//   }
// }

</script>

<template>
  <div class="cyber-container">
    <div class="cyber-card">
      <div class="card-header">
        <h2>房间管理</h2>
        <div class="header-actions">
<!--          <el-button type="primary" @click="handlerAdd" class="cyber-button">-->
<!--            <el-icon><Plus /></el-icon>-->
<!--            新增房间-->
<!--          </el-button>-->
        </div>
      </div>

      <div class="cyber-form-card">
        <el-form :model="searchObj" label-width="100px" class="search-form">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="房间号">
                <el-input v-model="searchObj.room_number" placeholder="请输入房间号" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="searchObj.status" placeholder="请选择状态" clearable style="width: 100%">
                  <el-option label="有人" value="有人"></el-option>
                  <el-option label="无人" value="无人"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="电子设备">
                <el-input v-model="searchObj.electronics" placeholder="请输入电子设备" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="楼层">
                <el-input v-model="searchObj.floor" placeholder="请输入楼层" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="form-actions">
              <el-button type="primary" @click="search" class="cyber-button">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch" class="cyber-button">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="cyber-table-card">
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="room_number" label="房间号" />
          <el-table-column prop="status" label="状态" />
          <el-table-column prop="electronics" label="电子设备" />
          <el-table-column prop="floor" label="楼层" />
          <el-table-column prop="price" label="价格">
            <template #default="scope">
              <span>{{ scope.row.price || scope.row.roomType?.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型">
            <template #default="scope">
              <span>{{ scope.row.type || scope.row.roomType?.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button v-if="scope.row.status === '无人'" size="small" type="primary" @click="openBillDialog(scope.row)" class="cyber-button">
                下单
              </el-button>
<!--              <el-button size="small" @click="edit(scope.row)" class="cyber-button">-->
<!--                编辑-->
<!--              </el-button>-->
<!--              <el-button size="small" type="danger" @click="del(scope.row)" class="cyber-button danger">-->
<!--                删除-->
<!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchObj.current"
            v-model:page-size="searchObj.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" :title="isAdd ? '新增房间' : '编辑房间'" width="600px" class="cyber-dialog">
      <div class="dialog-glow"></div>
      <el-form :model="obj" label-width="100px" class="edit-form">
        <el-form-item label="房间号" prop="room_number">
          <el-input v-model="obj.room_number" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="obj.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="有人" value="有人"></el-option>
            <el-option label="无人" value="无人"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电子设备" prop="electronics">
          <el-input v-model="obj.electronics" placeholder="请输入电子设备" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="obj.floor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="obj.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model="obj.type" placeholder="请输入类型" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editWinVisible = false" class="cyber-button">取消</el-button>
          <el-button type="primary" @click="save" class="cyber-button primary">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 账单对话框 -->
    <el-dialog v-model="billDialogVisible" title="创建账单" width="600px" class="cyber-dialog">
      <div class="dialog-glow"></div>
      <el-form :model="billObj" label-width="100px" class="edit-form">
        <el-form-item label="员工ID" prop="staff_id">
          <el-input v-model="billObj.staff_id" placeholder="请输入员工ID" />
        </el-form-item>
        <el-form-item label="房费" prop="room_fee">
          <el-input v-model="billObj.room_fee" placeholder="请输入房费" type="number" />
        </el-form-item>
        <el-form-item label="其他费用" prop="extra_fee">
          <el-input v-model="billObj.extra_fee" placeholder="请输入其他费用" type="number" />
        </el-form-item>
        <el-form-item label="账单时间" prop="bill_time">
          <el-date-picker
            v-model="billObj.bill_time"
            type="date"
            placeholder="请选择账单时间"
            value-format="YYYY-MM-DD"
            format="YYYY/MM/DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="billDialogVisible = false" class="cyber-button">取消</el-button>
          <el-button type="primary" @click="submitBill" class="cyber-button primary">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 添加固定定位的联系电话信息 -->
  <div class="contact-info-fixed">
    联系电话13465134662
  </div>
</template>

<style scoped>
.cyber-container {
  padding: 20px;
  min-height: calc(100vh - 40px);
  position: relative;
  overflow-y: auto;
}

.cyber-card {
  background: rgba(20, 20, 40, 0.7);
  border-radius: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  border: 1px solid rgba(0, 243, 255, 0.2);
  backdrop-filter: blur(5px);
  position: relative;
  margin-bottom: 20px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(0, 243, 255, 0.2);
  background: rgba(15, 15, 30, 0.8);
  flex-shrink: 0;
}

.card-header h2 {
  color: #00f3ff;
  font-size: 22px;
  margin: 0;
  text-shadow: 0 0 10px rgba(0, 243, 255, 0.5);
}

.cyber-form-card {
  padding: 20px;
  background: rgba(25, 25, 45, 0.6);
  margin: 20px;
  border-radius: 8px;
  border: 1px solid rgba(0, 243, 255, 0.1);
  flex-shrink: 0;
}

.cyber-table-card {
  padding: 0 20px 20px;
  flex: 1;
  overflow-y: auto;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.search-form .el-input__wrapper {
  background: rgba(10, 10, 25, 0.5);
  border: 1px solid rgba(0, 243, 255, 0.3);
  box-shadow: 0 0 5px rgba(0, 243, 255, 0.2);
}

.search-form .el-input__wrapper.is-focus {
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.4);
}

.form-actions {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  margin-top: 10px;
}

.cyber-button {
  background: rgba(50, 50, 80, 0.7);
  border: 1px solid rgba(0, 243, 255, 0.5);
  color: #00f3ff;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.cyber-button:hover {
  background: rgba(0, 243, 255, 0.2);
  box-shadow: 0 0 15px rgba(0, 243, 255, 0.4);
  border-color: #00f3ff;
}

.cyber-button.primary {
  background: linear-gradient(90deg, #00f3ff, #00aaff);
  border: 1px solid #00f3ff;
  color: #000;
  font-weight: 600;
}

.cyber-button.primary:hover {
  background: linear-gradient(90deg, #00aaff, #00f3ff);
  box-shadow: 0 0 20px rgba(0, 243, 255, 0.6);
}

.cyber-button.danger {
  background: linear-gradient(90deg, #ff0055, #ff0000);
  border: 1px solid #ff0055;
  color: #fff;
}

.cyber-button.danger:hover {
  background: linear-gradient(90deg, #ff0000, #ff0055);
  box-shadow: 0 0 20px rgba(255, 0, 85, 0.6);
}

.cyber-table-card :deep(.el-table) {
  background: rgba(20, 20, 40, 0.7);
  border: 1px solid rgba(0, 243, 255, 0.2);
  color: #e0e0ff;
}

.cyber-table-card :deep(.el-table__header th) {
  background: rgba(15, 15, 30, 0.9);
  color: #00f3ff;
  font-weight: 600;
}

.cyber-table-card :deep(.el-table__row:hover) {
  background: rgba(0, 243, 255, 0.1);
}

.cyber-table-card :deep(.el-table__row) {
  background: rgba(25, 25, 45, 0.5);
}

.cyber-table-card :deep(.el-table__cell) {
  border-color: rgba(0, 243, 255, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  flex-shrink: 0;
}

.cyber-dialog :deep(.el-dialog) {
  background: rgba(20, 20, 40, 0.95);
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #00f3ff;
  box-shadow: 0 0 30px rgba(0, 243, 255, 0.3);
  backdrop-filter: blur(10px);
  position: relative;
}

.dialog-glow {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00f3ff, #ff00ff, transparent);
  z-index: 10;
}

.cyber-dialog :deep(.el-dialog__header) {
  background: rgba(10, 10, 25, 0.9);
  color: #ffffff;
  padding: 18px 20px;
  border-bottom: 1px solid rgba(0, 243, 255, 0.3);
  position: relative;
}

.cyber-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
  text-shadow: 0 0 5px rgba(0, 243, 255, 0.7);
}

.edit-form {
  padding: 20px;
}

.edit-form :deep(.el-form-item__label) {
  color: #00f3ff;
  text-shadow: 0 0 5px rgba(0, 243, 255, 0.5);
}

.edit-form :deep(.el-input__wrapper) {
  background: rgba(10, 10, 25, 0.5);
  border: 1px solid rgba(0, 243, 255, 0.3);
  box-shadow: 0 0 5px rgba(0, 243, 255, 0.2);
}

.edit-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.4);
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 10px;
}

.contact-info-fixed {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: rgba(0, 243, 255, 0.1);
  border: 1px solid rgba(0, 243, 255, 0.3);
  border-radius: 8px;
  padding: 10px 15px;
  color: #00f3ff;
  font-size: 14px;
  backdrop-filter: blur(5px);
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.2);
  z-index: 1000;
}
</style>
